package com.power.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.power.domain.Order;
import com.power.model.Result;
import com.power.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @Description 订单业务模块控制层
 * @Author dingchunlin
 * @Date 2024/07/20 17:01
 * @Version 1.0.0
 */
@Api(tags = "订单业务接口管理")
@RestController
@RequestMapping("/order/order")
public class SysOrderController {

    @Autowired
    private OrderService orderService;


    @ApiOperation(value = "多条件分页查询订单")
    @GetMapping("/page")
    @PreAuthorize("hasAnyAuthority('order:order:page')")
    public Result<Page<Order>> loadOrderPage(@RequestParam Long current,
                                       @RequestParam Long size,
                                       @RequestParam(required = false) String orderNumber,
                                        @RequestParam(required = false) Integer status,
                                        @RequestParam(required = false) Date startTime,
                                        @RequestParam(required = false) Date endTime) {
        //创建订单分页对象
        Page<Order> page = new Page<>(current, size);
        //多条件分页查询订单
        page = orderService.queryOrderPage(page, orderNumber, status, startTime, endTime);
        return Result.success(page);
    }

    /**
     * 根据订单编号查询订单详情
     * @param orderNumber 订单编号
     * @return 订单详情
     */
    @ApiOperation(value = "根据订单编号查询订单详情")
    @GetMapping("/orderInfo/{orderNumber}")
    @PreAuthorize("hasAnyAuthority('order:order:info')")
    public Result<Order> loadOrderDetail(@PathVariable String orderNumber) {
        Order order = orderService.queryOrderDetailByOrderNumber(orderNumber);
        return Result.success(order);
    }

    @ApiOperation(value = "导出销售记录")
    @GetMapping("/soldExcel")
    @PreAuthorize("hasAnyAuthority('order:order:soldExcel')")
    public Result<String> exportSoldOrderRecordExcel() {
        // 查询所有销售记录
        List<Order> orderList = orderService.list(new LambdaQueryWrapper<Order>()
                .orderByDesc(Order::getCreateTime)
        );
        // 导出Excel
        String fileName = "销售记录-" + System.currentTimeMillis() + ".xlsx";

        EasyExcel.write(fileName, Order.class).sheet("销售记录").doWrite(orderList);
        return Result.success(null);
    }
}
